﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace TripleGameService
{
    public class TripleGameService : ITripleGameService
    {
        public PlayerDTO GetPlayerById(string idAsString) 
        {
            int id = int.Parse(idAsString);
            TripleEntities context = new TripleEntities();
            PlayerDTO found = new PlayerDTO();
            foreach (var player in context.Players) 
            {
                if (player.PlayerId == id)
                {
                    found = PlayerDTO.CreateFromUser(player);
                }
            }
            return found;
        }

        public int GetGameState(string gameIdAsString) 
        {
            int gameId = int.Parse(gameIdAsString);
            TripleEntities context = new TripleEntities();
            foreach (var game in context.Games) 
            {
                if (game.GameId == gameId) 
                {
                    return game.StateId;
                }
            }
            throw new ArgumentException("No such game");
        }

        public void CreatePlayer(string playerName) 
        {
            TripleEntities context = new TripleEntities();
            Player newPlayer = new Player();
            newPlayer.PlayerName = playerName;
            context.Players.AddObject(newPlayer);
            context.SaveChanges();
        }

        public void UpdateGameState(string gameIdAsString, string gameStateAsString) 
        {
            TripleEntities context = new TripleEntities();
            int gameId = int.Parse(gameIdAsString);
            int gameState = int.Parse(gameStateAsString);

            foreach (var game in context.Games) 
            {
                if (game.GameId == gameId) 
                {
                    game.StateId = gameState;
                    break;
                }
            }
            context.SaveChanges();
        }

        public void UpdateBoardState(string gameIdAsString, string boardState) 
        {
            int gameId = int.Parse(gameIdAsString);
            TripleEntities context = new TripleEntities();
            foreach (var game in context.Games) 
            {
                if (game.GameId == gameId) 
                {
                    game.BoardState = boardState;
                    break;
                }
            }
            context.SaveChanges();
        }

        public IEnumerable<GameDTO> GetAllGames() 
        {
            TripleEntities context = new TripleEntities();

            var games = context.Games.OrderBy(g => g.GameId).ToList();

            IEnumerable<GameDTO> gamesDTOs = games.Select(g => GameDTO.CreateFromGame(g));
            return gamesDTOs;
        }
    }
}
